package member

import (
	"context"
	"group-buy/group_buy/internal/models"
	"time"

	"group-buy/group_buy/internal/svc"
	"group-buy/group_buy/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type FindBusinessMemberLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFindBusinessMemberLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FindBusinessMemberLogic {
	return &FindBusinessMemberLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FindBusinessMemberLogic) FindBusinessMember(req *types.FindBusinessMemberReq) (resp *types.FindBusinessMemberRsp, err error) {
	data := make([]*models.BusinessMember, 0)
	sql := l.svcCtx.Engine.Where("")
	if req.BusinessId > 1 {
		sql = sql.And("business_id=?", req.BusinessId)
	}
	if req.MemberId > 0 {
		sql = sql.And("member_id=?", req.MemberId)
	}
	if req.InviteId > 0 {
		sql = sql.And("invite_id=?", req.InviteId)
	}
	if req.IsIndependence > 0 {
		sql = sql.And("is_independence=?", req.IsIndependence)
	}
	count, err := sql.Limit(req.Size, (req.Page-1)*req.Size).Desc("id").FindAndCount(&data)
	if err != nil {
		return nil, err
	}
	list := make([]*types.BusinessMember, len(data), len(data))

	for i, _ := range data {
		business := &models.Business{Id: data[i].BusinessId, UserId: data[i].MemberId}
		exist, _ := l.svcCtx.Engine.Exist(business)

		list[i] = &types.BusinessMember{
			Id:             data[i].Id,
			MemberId:       data[i].MemberId,
			MemberName:     data[i].MemberName,
			BusinessId:     data[i].BusinessId,
			BusinessName:   data[i].BusinessName,
			InviteId:       data[i].InviteId,
			IsIndependence: data[i].IsIndependence,
			MemberPhone:    data[i].MemberPhone,
			CareatAt:       data[i].CreateAt.Format(time.DateTime),
			IsLb:           exist,
		}
	}

	return &types.FindBusinessMemberRsp{List: list, Count: count}, nil
}
